//
//  PQHttp.m
//  Traiana Harmony
//
//  Created by Barak Edry on 7/26/12.
//
//

#import "PQHttpRequest.h"

@implementation PQHttpRequest


+ (void) getFromURL:(NSURL*)url response:(QPResponseCallback)callback {
    NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    urlRequest.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                           
                                           if ([data length] >0 && error == nil)
                                           {
                                               
                                               // DO YOUR WORK HERE
                                               NSError* jsonError;
                                               NSString *txt = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
                                               callback(txt, jsonError);
                                               
                                           }
                                           else if ([data length] == 0 && error == nil)
                                           {
                                               NSLog(@"Nothing was downloaded.");
                                               callback(nil, error);
                                           }
                                           else if (error != nil){
                                               NSLog(@"Error = %@", error);
                                               callback(nil, error);
                                           }
                                           
                                       }];
}

+ (void) postToURL:(NSURL*)url withData:(NSDictionary*)data response:(QPResponseCallback)callback{
    
    NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    urlRequest.HTTPMethod = @"POST";
    
    
    if (data != nil){
        NSData* body = [self encodeDictionary:data];
        [urlRequest setValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField:@"Content-Length"];
        [urlRequest setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [urlRequest setHTTPBody:body];
    }
    
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                           
                                           if ([data length] >0 && error == nil)
                                           {
                                               
                                               // DO YOUR WORK HERE
                                               NSError* jsonError;
                                               NSString *txt = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
                                               callback(txt, jsonError);
                                               
                                           }
                                           else if ([data length] == 0 && error == nil)
                                           {
                                               NSLog(@"Nothing was downloaded.");
                                               callback(nil, error);
                                           }
                                           else if (error != nil){
                                               NSLog(@"Error = %@", error);
                                               callback(nil, error);
                                           }
                                           
                                       }];
    
    
}


+ (void) putToURL:(NSURL*)url withData:(NSDictionary*)data response:(QPResponseCallback)callback{
    
    NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    urlRequest.HTTPMethod = @"PUT";
    
    
    if (data != nil){
        NSData* body = [self encodeDictionary:data];
        [urlRequest setValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField:@"Content-Length"];
        [urlRequest setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [urlRequest setHTTPBody:body];
    }
    
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                           
                                           if ([data length] >0 && error == nil)
                                           {
                                               
                                               // DO YOUR WORK HERE
                                               NSError* jsonError;
                                               NSString *txt = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
                                               callback(txt, jsonError);
                                               
                                           }
                                           else if ([data length] == 0 && error == nil)
                                           {
                                               NSLog(@"Nothing was downloaded.");
                                               callback(nil, error);
                                           }
                                           else if (error != nil){
                                               NSLog(@"Error = %@", error);
                                               callback(nil, error);
                                           }
                                           
                                       }];
    
    
}

+ (void) getJSONFromURL:(NSURL*)url response:(QPJSONSResponseCallback)callback{
    
    NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    urlRequest.HTTPMethod = @"GET";
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"request url %@", url);
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                           NSLog(@"data length %d", [data length]);
                                           
                                           if ([data length] >0 && error == nil)
                                           {
                                               
                                               // DO YOUR WORK HERE
                                               NSError* jsonError;
                                               id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&jsonError];
                                               callback(obj, jsonError);
                                               
                                           }
                                           else if ([data length] == 0 && error == nil)
                                           {
                                               NSLog(@"Nothing was downloaded.");
                                               callback(nil, error);
                                           }
                                           else if (error != nil){
                                               NSLog(@"Error = %@", error);
                                               callback(nil, error);
                                           }
                                           
                                       }];
}

+ (void) postJSONToURL:(NSURL*)url withData:(NSDictionary*)data response:(QPJSONSResponseCallback)callback {
    
    NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    urlRequest.HTTPMethod = @"POST";
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    if (data != nil){
        NSData* body = [NSJSONSerialization dataWithJSONObject:data options:0 error:nil];
        [urlRequest setValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField:@"Content-Length"];
        [urlRequest setValue:@"application/json charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [urlRequest setHTTPBody:body];
    }
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                           
                                           if ([data length] >0 && error == nil)
                                           {
                                            
                                               
                                               // DO YOUR WORK HERE
                                               NSError* jsonError;
                                               id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&jsonError];
                                               callback(obj, jsonError);
                                               
                                           }
                                           else if ([data length] == 0 && error == nil)
                                           {
                                               NSLog(@"Nothing was downloaded.");
                                               callback(nil, error);
                                           }
                                           else if (error != nil){
                                               NSLog(@"Error = %@", error);
                                               callback(nil, error);
                                           }
                                           
                                       }];
    
}

+ (void) basicAuthToURL:(NSURL*)url username:(NSString*)username password:(NSString*)password response:(QPResponseCallback)callback {
    
}

+ (NSData*)encodeDictionary:(NSDictionary*)dictionary {
    NSMutableArray *parts = [[NSMutableArray alloc] init];
    for (NSString *key in dictionary) {
        NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue];
        [parts addObject:part];
    }
    NSString *encodedDictionary = [parts componentsJoinedByString:@"&"];
    return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}

@end